<template>
	<view class="diet">
		<post-nav-bar title="饮食管理"></post-nav-bar>
		<view class="blank"></view>
		<up-sticky bgColor="#F8F8FF">
			<up-tabs :list="tabList" :current="current" lineWidth="80" lineColor="#FF4D4F"
				itemStyle="padding-left: 40px; padding-right: 40px; height: 40px; width: 200px" :activeStyle="{
			    color: '#FF4D4F',
			    fontWeight: 550,
			    transform: 'scale(1.05)'
			}" :inactiveStyle="{
			    color: '#606266',
			    transform: 'scale(1)'
			}" @click="tabChange">
			</up-tabs>
		</up-sticky>

		<view v-if="current == 0" class="diet-tab">
			<Line></Line>
			<view class="select-time" @click="show = true;">
				<view>
					<text class="select-time-title" style="color: grey;">就餐时间</text>
					<text style="color: #FF4D4F;"> *</text>
				</view>
				<view class="select-time-content">
					<text v-if="!time">请选择</text>
					<text v-else>{{time}}</text>
				</view>
				<view class="select-time-icon">
					<up-icon name="arrow-right"></up-icon>
				</view>
			</view>
			<up-picker :show="show" :columns="columns" @confirm="confirm" @cancel="cancel" :closeOnClickOverlay="true"
				@close="close" confirmColor="#FF4D4F"></up-picker>
			<Line></Line>
			<view class="text-input">
				<view class="text-input-title" style="color: grey;">文字描述</view>
				<view class="text-input-content">
					<up-textarea v-model="textValue" placeholder="今天吃了什么？" autoHeight height="100"></up-textarea>
				</view>
			</view>
			<Line></Line>
			<view class="upload">
				<view class="upload-title" style="color: grey;">上传图片</view>
				<view class="upload-content">
					<uni-file-picker limit="1" @select="handleSelect" @delete="handleDelete"></uni-file-picker>
				</view>
			</view>
			<button class="submit-button" @click="getNutrition">提交</button>
			<view class="nutrition-box">
				<view class="nutrition-item" v-for="(item, index) in nutritionData" :key="index"
					style="font-size: 18px;">
					{{item.content}}
				</view>
			</view>
		</view>
		<view v-else-if="current == 1" class="report">
			<Line></Line>
			<view class="date-picker">
				<up-cell-group>
					<up-cell @click="showCalendar=true" title="选择日期" :label="date" size="large" isLink></up-cell>
				</up-cell-group>
				<up-calendar color="#FF4D4F" mode="single" :show="showCalendar" @confirm="confirmCalendar" monthNum="13"
					:closeOnClickOverlay="true" @close="closeCalendar" :maxDate="maxDate"
					:minDate="minDate"></up-calendar>
			</view>
			<view class="report-content">
				<view class="report-item" v-for="(item, index) in reportData" :key="index" style="font-size: 18px;">
					{{item.content}}
				</view>
			</view>
			<up-gap height="60"></up-gap>
			<button class="confirm-button" @click="showData">确定</button>
		</view>
		<up-modal :show="show1" @confirm="show1 = false" content='请选择就餐时间' confirmColor="#FF4D4F"></up-modal>
		<up-modal :show="show2" @confirm="show2 = false" content='文字描述或上传图片不能为空' confirmColor="#FF4D4F"></up-modal>
	</view>
</template>

<script setup>
	import Line from '@/components/Line.vue'
	import {
		appUrl
	} from '../../main';
	import {
		ref,
		reactive
	} from 'vue';

	const tabList = reactive([{
			name: '今日记录'
		},
		{
			name: '往日报告'
		},
	]);
	let current = ref(0)

	const tabChange = (item) => {
		if (item.index == 0) {
			console.log('item', item);
		} else if (item.index == 1) {
			console.log('item', item);
		} else {
			console.log('item', item);
		}
		current.value = item.index
	}

	const show = ref(false);
	const show1 = ref(false);
	const show2 = ref(false);
	const showCalendar = ref(false);
	const time = ref('');
	const date = ref('');

	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const maxDate = `${year}-${month}-${day}`; // 设置最大日期为当前日期

	const oneYearAgo = new Date(now.setFullYear(now.getFullYear() - 1));
	const year1 = oneYearAgo.getFullYear();
	const month1 = String(oneYearAgo.getMonth() + 1).padStart(2, '0');
	const day1 = String(oneYearAgo.getDate()).padStart(2, '0');
	const minDate = `${year1}-${month1}-${day1}`;

	const columns = reactive([
		['早餐', '午餐', '晚餐', '其他']
	]);
	const confirm = (e) => {
		time.value = e.value[0];
		show.value = false;
	};
	const cancel = () => {
		show.value = false;
	};
	const close = () => {
		show.value = false;
	};
	const confirmCalendar = (e) => {
		showCalendar.value = false;
		date.value = e[0];
	};
	const closeCalendar = () => {
		showCalendar.value = false;
	};
	const textValue = ref('');

	let reportData = ref([])
	let nutritionData = ref([])

	const userId = uni.getStorageSync("userId");
	let filePath = ref('');

	const handleSelect = (e) => {
		filePath = e.tempFilePaths[0];
	}
	const handleDelete = () => {
		filePath = ref('');
	}

	const back = () => {
		uni.navigateBack()
	}
	const getNutrition = () => {
		if (time.value == '') {
			show1.value = true;
		} else if (filePath.value == '' && textValue.value == '') {
			show2.value = true;
		} else if (filePath.value == '') {
			uni.showToast({
				icon:'loading',
				title:"正在生成",
				duration: 10000
			})
			uni.request({
				url: `http://120.26.113.115:5000/dietary_record/${userId}`,
				data: {
					text: textValue.value,
					meal_type: time.value,
					food_item: textValue.value,
					date: maxDate
				},
				method: "post"
			}).then((res) => {
				if (res.statusCode == 200) {
					nutritionData.value = res.data;
					uni.showToast({
						title: "成功"
					})
				} else {
					console.log('服务异常');
				}
			})
		} else {
			uni.showToast({
				icon:'loading',
				title:"正在生成",
				duration: 10000
			})
			uni.uploadFile({
				url: `http://120.26.113.115:5000/dietary_record/${userId}`,
				filePath: filePath,
				fileType: 'image',
				name: 'file',
				formData: {
					text: textValue.value,
					meal_type: time.value,
					food_item: textValue.value,
					date: maxDate
				},
				success: (res) => {
					nutritionData.value = JSON.parse(res.data);
					uni.showToast({
						title: "成功"
					})
				}
			});
		}
	}

	const showData = async () => {
		try {
			uni.showToast({
				icon:'loading',
				title:"正在生成",
				duration: 10000
			})
			uni.request({
				url: 'http://120.26.113.115:5000/health_report',
				data: {
					user_id: userId,
					date: date.value
				},
				method: "POST"
			}).then((res) => {
				if (res.statusCode == 200) {
					reportData.value = res.data;
					uni.showToast({
						title: "成功"
					})
				} else if (res.statusCode == 201) {
					reportData.value = [{
						content: "该日无记录"
					}];
					uni.showToast({
						title: "成功"
					})
				} else {
					console.log('服务异常');
				}
			})
		} catch (error) {
			console.error('请求失败:', error);
		}
	}
</script>

<style lang="scss" scoped>
	.blank {
		height: 60rpx;
		background-color: ghostwhite;
		position: fixed;
		top: 70rpx;
		left: 0;
		width: 100%;
		z-index: 8;
	}

	.diet {
		background-color: #FFFFFF;

		.diet-tab {

			.select-time {
				padding: 30rpx;
				display: flex;
				align-items: center;
			}

			.select-time-title {}

			.select-time-content {
				display: flex;
				padding-left: 50rpx;
			}

			.select-time-icon {
				margin-left: auto;
			}

			.text-input {
				.text-input-title {
					padding-top: 30rpx;
					padding-left: 30rpx;
				}

				.text-input-content {
					background-color: #FFFFFF;
					padding: 30rpx;
				}
			}

			.upload {
				padding-top: 30rpx;

				.upload-title {
					padding-left: 30rpx;
					padding-bottom: 10rpx;
				}

				.upload-content {
					background-color: #FFFFFF;
					padding-left: 30rpx;
					padding-top: 30rpx;
					padding-bottom: 40rpx;
				}
			}

			.nutrition-box {
				padding: 30rpx;
			}

			.nutrition-item {
				padding: 20rpx;
				background-color: rgba(255, 190, 187, 0.2);
			}

			.submit-button {
				background-color: #ff4d4f;
				color: #F5F5F5;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 92%;
			}
		}

		.report {
			background-color: #FFFFFF;

			.report-content {
				padding: 30rpx;

			}

			.report-item {
				padding: 20rpx;
				background-color: rgba(255, 190, 187, 0.2);
				border-radius: 10px;
				border: 1px solid #ff4d4f;
			}

			.confirm-button {
				background-color: #ff4d4f;
				color: #F5F5F5;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				position: fixed;
				bottom: 30rpx;
				left: 30rpx;
				width: 92%;
			}

		}


	}
</style>